package org.xtense.engine.actions;

import java.text.MessageFormat;
import java.util.Iterator;

import org.xtense.data.DBManager;
import org.xtense.engine.IConstants;
import org.xtense.exception.XtenseException;
import org.xtense.log.iLog;

public class DeleteAction extends XAction {
	
	public DeleteAction(String documentName) {
		super(new DBManager(), documentName);
	}

	public DeleteAction(DBManager manager, String documentName) {
		super(manager, documentName);
		documentID = super.getDocumentIDfromName(manager, documentName);
		if (documentID < 0) {
			try {
				throw new XtenseException(XtenseException.NoSuchDoc);
			} catch (XtenseException e) {
				iLog.warn(e);
			}
		}
	}

	public DeleteAction(DBManager manager, int documentID) {
		super(manager, documentID);
	}
	
	@Override
	public Object execute(Object object) {
		String docIdExpr = MessageFormat.format(IConstants.Sql_Int_Equal,
				new Object[] { IConstants.Document_ID, documentID });
		String sql;
		String table;
		Iterator<String> iterator;
		for ( iterator = IConstants.AETPtables.values().iterator(); iterator
				.hasNext();) {
			table = iterator.next();
			sql = MessageFormat.format(IConstants.Sql_Delete, new Object[] {
					table, docIdExpr });
			iLog.info("Delete from... " + table);
			database.executeSqlUpdate(sql);
		}
		for (iterator = IConstants.Dtables.values().iterator(); iterator
				.hasNext();) {
			table = iterator.next();
			sql = MessageFormat.format(IConstants.Sql_Delete, new Object[] {
					table, docIdExpr });
			iLog.info("Delete from... " + table);
			database.executeSqlUpdate(sql);
		}
		iLog.info("Finish delete the document.");
		return null;
	}

}
